/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tom.tommessenger3;

import static com.tom.tommessenger3.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.tom.tommessenger3.CommonUtilities.EXTRA_MESSAGE;
import static com.tom.tommessenger3.CommonUtilities.SENDER_ID;
import static com.tom.tommessenger3.CommonUtilities.SERVER_URL;
import com.tom.tommessenger3.db.MessageDBOpenHelper;

import com.google.android.gcm.GCMRegistrar;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ArrayAdapter; 
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;
import android.database.Cursor;

import java.util.ArrayList; 
import java.util.List;



/**
 * Main UI for the demo app.
 */
public class DemoActivity extends Activity {

	private ArrayList<Message> mSenderList;
	private Message mSenderItem = null;
	private SenderMessageCustomAdapter mAdapter;
	private ListView mSenderListView;
	private MessageDBOpenHelper mDbOpenHelper;
	private Cursor mCursor;
	
    AsyncTask<Void, Void, Void> mRegisterTask;
    private static final String TAG = "DemoActivity";
    

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkNotNull(SERVER_URL, "SERVER_URL");
        checkNotNull(SENDER_ID, "SENDER_ID");
        
        setContentView(R.layout.main);
        
        mSenderListView = (ListView)findViewById(R.id.sender_list);
        
        mSenderList = new ArrayList<Message>();
		mAdapter = new SenderMessageCustomAdapter(this, R.layout.sender_list_view_row, mSenderList);
		mSenderListView.setAdapter(mAdapter);
		mSenderListView.setCacheColorHint(0);
		
		
		mSenderListView.setOnItemClickListener(new OnItemClickListener() {
			   public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
			     long arg3) {
			    ItemClick(arg0,arg1,arg2,arg3);
			    
			   }
		 });
		
	    // DB Create and Open
        mDbOpenHelper = new MessageDBOpenHelper(this);
        mDbOpenHelper.open();

        updateSenderListViewFromDB();
        
        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);
        //setContentView(R.layout.main);
        
        //mDisplay = (TextView) findViewById(R.id.display);
        registerReceiver(mHandleMessageReceiver,
                new IntentFilter(DISPLAY_MESSAGE_ACTION));
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
            // Automatically registers application on startup.
            GCMRegistrar.register(this, SENDER_ID);
        } else {
            // Device is already registered on GCM, check server.
            if (GCMRegistrar.isRegisteredOnServer(this)) {
                // Skips registration.
            	//salva
            	Log.i(TAG, getString(R.string.already_registered));
                //mDisplay.append(getString(R.string.already_registered) + "\n");
            } else {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        boolean registered =
                                ServerUtilities.register(context, regId);
                        // At this point all attempts to register with the app
                        // server failed, so we need to unregister the device
                        // from GCM - the app will try to register again when
                        // it is restarted. Note that GCM will send an
                        // unregistered callback upon completion, but
                        // GCMIntentService.onUnregistered() will ignore it.
                        if (!registered) {
                            GCMRegistrar.unregister(context);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
                
                //updateSenderListViewFromDB();
            }
        }
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            /*
             * Typically, an application registers automatically, so options
             * below are disabled. Uncomment them if you want to manually
             * register or unregister the device (you will also need to
             * uncomment the equivalent options on options_menu.xml).
             */
            /*
            case R.id.options_register:
                GCMRegistrar.register(this, SENDER_ID);
                return true;
            case R.id.options_unregister:
                GCMRegistrar.unregister(this);
                return true;
             */
            case R.id.options_clear:
            	//salva
                //mDisplay.setText(null);
                return true;
            case R.id.options_exit:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        unregisterReceiver(mHandleMessageReceiver);
        GCMRegistrar.onDestroy(this);
        super.onDestroy();
    }
    
    /*
    // Only Test
    public boolean onKeyDown (int keyCode, KeyEvent event) {
    
    	String logMsg = "keyCode = " + keyCode;
    	Log.i(TAG, logMsg);
    	if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
    		//startActivity(new Intent("com.tom.tommessenger3.MessageHistoryActivity"));
            Message m = new Message("KBStar", "15883455", "Thank You!", "2013-01-01-23-00");
            mAdapter.add(m);
        	mAdapter.notifyDataSetChanged();
     	}
    	return false;
    }
    */

    /*
    @Override
    protected void onListItemClick (ListView l, View v, int position, long id){
    	super.onListItemClick(l, v, position, id);
    	Toast.makeText(this, l.get.get(position), Toast.LENGTH_SHORT).show();
    }
    */
    
    private void checkNotNull(Object reference, String name) {
        if (reference == null) {
            throw new NullPointerException(
                    getString(R.string.error_config, name));
        }
    }


    private final BroadcastReceiver mHandleMessageReceiver =
            new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);

            Message m = new Message(newMessage);
            
            // last salva
            //long success = mDbOpenHelper.insertColumn(m);
            //String result = "Insert Column " + m.getsenderNumber() + ": success-" + success;
            //Log.i(TAG, result);
            
            //mAdapter.add(m);
        	//mAdapter.notifyDataSetChanged();
        	
        	String suppressed_msg = m.getmsgBody().substring(0, Math.min(m.getmsgBody().length(), 18)) + "...";
        	CommonUtilities.generateNotification(context, suppressed_msg);
        	
        	updateSenderListViewFromDB();

        }
    };
    
    void ItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3){
    	Message m = mSenderList.get(arg2);
    	Intent intent = new Intent(DemoActivity.this, com.tom.tommessenger3.MessageHistoryActivity.class);
    	intent.putExtra(Message.SENDER_NUMBER, m.getsenderNumber());
    	//Log.i(TAG, )

    	startActivity(intent);
    }//ItemClick
    
    void updateSenderListViewFromDB(){
        mCursor = null;
        
        mCursor = mDbOpenHelper.getSenderTable();
        Log.e(TAG, "Message DB COUNT = " + mCursor.getCount());
        
        mAdapter.clear();
        
        while (mCursor.moveToNext()) {
  
        	this.mSenderItem = new Message(
        			mCursor.getLong(mCursor.getColumnIndex("_id")),
        			mCursor.getString(mCursor.getColumnIndex(Message.SENDER_NAME)),
        			mCursor.getString(mCursor.getColumnIndex(Message.SENDER_NUMBER)),
        			mCursor.getString(mCursor.getColumnIndex(Message.MESSAGE_BODY)),
        			mCursor.getString(mCursor.getColumnIndex(Message.ISSUE_DATE)));
        	Log.i(TAG, mCursor.getString(mCursor.getColumnIndex(Message.MESSAGE_BODY)));
           
        	mAdapter.add(mSenderItem);
            //mInfoArray.add(mInfoClass);
        }
        
     	mAdapter.notifyDataSetChanged();
        mCursor.close();
    }

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}
    

}